package org.wlw.web.dao.impl;

import org.apache.ibatis.session.SqlSession;
import org.wlw.web.mapper.BaseMapper;
import org.wlw.web.utils.DBUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

public class BaseDao <T,M extends BaseMapper>{

    private Class<M> getType() {
        Type type = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        Class<M> mapperClass = (Class<M>) type;
        return mapperClass;
    }
    public void add(T t) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DBUtils.openSession();
            sqlSession.getMapper(getType()).add(t);
            sqlSession.commit();
        } finally {
            DBUtils.close(sqlSession);
        }
    }

    public void update(T t) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DBUtils.openSession();
            sqlSession.getMapper(getType()).update(t);
            sqlSession.commit();
        } finally {
            DBUtils.close(sqlSession);
        }
    }

    public void delete(int id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DBUtils.openSession();
            sqlSession.getMapper(getType()).delete(id);
            sqlSession.commit();
        } finally {
            DBUtils.close(sqlSession);
        }
    }

    public T load(int id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DBUtils.openSession();
            return (T)sqlSession.getMapper(getType()).load(id);
        } finally {
            DBUtils.close(sqlSession);
        }
    }

    public List<T> find(T t) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DBUtils.openSession();
            return (List<T>)sqlSession.getMapper(getType()).find(t);
        } finally {
            DBUtils.close(sqlSession);
        }
    }
}
